﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebMvc.Areas.Sys.Models;
using WebMvc.Controllers;
using WebMvc.Models;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace WebMvc.Areas.Sys.Controllers
{
    [Area("Sys")]
    [Authorize(Roles = "super")]
    public class UserController : BaseController<User>
    {
        public UserController(EFDbContext context) : base(context)
        {
        }

        public JsonResult GetUserByDepartment(int pageIndex, int departmentId)
        {
            var rowCount = 0;
            var totalPages = 0;
            var result = GetPagedEntitysByLambdaAndSort(pageIndex, PageSize, out rowCount, out totalPages, o => o.DepartmentId == departmentId, OrderLambda, IsASC);
            return Json(new
            {
                rowCount = rowCount,
                pageCount = totalPages,
                rows = result,
            });
        }

        /// <summary>
        /// 根据用户Id获取用户信息以及其所属于的角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>        
        public JsonResult GetUserWithRoles(int userId)
        {
            var user = _context.Set<User>().SingleOrDefault(m => m.Id == userId);
            IList<UserRole> _roles = new List<UserRole>();
            if (user != null)
            {
                UserRoleController _service = new UserRoleController(base._context);
                _roles = _service.GetEntitysByLambdaAndSort(o => o.UserId == user.Id, o => o.SortIndex, true).ToList();

            }
            return Json(new { user = user, roles = _roles });
        }
        
        [HttpGet, Authorize]
        public IActionResult ModifyPsw()
        {
            return View();
        }

        [HttpPost, Authorize]
        public async Task<IActionResult> ModifyPsw(User item, string oldPsw)
        {
            try
            {                
                var getItemById =await GetById(item.Id);
                if (getItemById.Password != oldPsw)
                {
                    return Json(new
                    {
                        Result = "Faild",
                        Message = "原密码错误"
                    });
                }
                getItemById.Password = item.Password;
                await ModifyEntity(getItemById);

                //退出当前用户的登录，删除登录的cookie信息
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                return Json(new { Result = "Success" });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// 检查用户是存在，用于登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>存在返回用户实体，否则返回NULL</returns>
        public User CheckUser(string loginId, string password)
        {
            return GetEntitysByLambdaAndSort(it => it.LoginId == loginId && it.Password == password,OrderLambda,IsASC).ToList().SingleOrDefault();
        }
                
        [HttpGet, AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            // Clear the existing external cookie to ensure a clean login process
            //await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost, AllowAnonymous]
        public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (ModelState.IsValid)
            {               
                //检查用户信息
                var user = CheckUser(model.LoginId, model.Password);
                if (user != null)
                {
                    if (user.IsLock)
                    {
                        ViewBag.ErrorInfo = "用户不存在或已被锁定。";
                        return View();
                    }

                    //根据user.roleid获取用户所对应的角色
                    RoleController _rs = new RoleController(base._context);
                    var role = await _rs.GetById(user.RoleId);

                    var userIdentity = new ClaimsIdentity(role.Name);   // 指定身份认证类型(登录的是什么角色)

                    userIdentity.AddClaim(new Claim(ClaimTypes.Role, role.Code));  //获取角色编码，用于在控制器上使用
                    userIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString()));  // 用户名称，以用户Id代替，因为NavigationViewComponent.cs中只能获取到User.Identity.Name
                    userIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserName));    // 用户姓名

                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    //创建Cookie保存自己的信息，必须要初始化一个ClaimsPrincipal（类型）来序列化和保存你想保存的用户信息到Cookie中。
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal,
                        new AuthenticationProperties
                        {
                            ExpiresUtc = DateTime.UtcNow.AddMinutes(90),
                            IsPersistent = false,
                            AllowRefresh = false
                        });

                    var ip = HttpContext.Connection.RemoteIpAddress.ToString();
                    //Logger.Info("-------------------------------登录----------------------------------");
                    //Logger.Info(user.UserName + "(" + user.LoginId + ")登录成功。登录IP:" + ip);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return Redirect("/Sys/Home/Index");
                    }

                    //记录Session
                    //HttpContext.Session.SetString("CurrentUserId", user.Id.ToString());
                    //HttpContext.Session.SetString("CurrentUserName", user.UserName);
                    //HttpContext.Session.Set("CurrentUser", Utility.ByteConvertHelper.Object2Bytes(user));
                    //跳转到系统首页
                    //return RedirectToAction("Index", "Home");
                }
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }
            return View(model);
        }

        [AllowAnonymous]
        public async Task<IActionResult> Logout()
        {
            //退出当前用户的登录，删除登录的cookie信息
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            //HttpContext.Session.Clear();
            return Redirect("~/Home/Index");
        }
    }
}
